package com.zhf.cloud.gateway.springcloudgateway.utils;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: 曾鸿发
 * @create: 2021-11-22 09:56
 * @description：获取登录用户信息
 **/
@Component
public class AuthUtil {

    public static Map<String,Object> getCurrentUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
            authentication = oAuth2Auth.getUserAuthentication();
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
                Map map = (Map) authenticationToken.getDetails();
                map = (Map) map.get("principal");
                return map;
            }
        }
        return null;
    }

}
